import { Request, RequestHandler, Response } from "express";
import {
  IGetResearchGroupByIdReq,
  IAddResearchGroupReq,
  IUpdateResearchGroupReq,
  IDeleteResearchGroupReq,
} from "../../models/research-group.model";
import * as ResearchGroupService from "../services/research-group.service";

/**
 * Get active researchGroup records
 *
 * @param req Express Request
 * @param res Express Response
 */
export const getResearchGroups: RequestHandler = async (
  req: Request,
  res: Response
) => {
  console.log(req.query)
  try {
    const researchGroups = await ResearchGroupService.getResearchGroups();

    res.status(200).json({
      data: researchGroups,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[researchGroups.controller][getResearchGroups][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "课题组列表获取失败！",
    });
  }
};

/**
 * Get researchGroup record based on id provided
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const getResearchGroupById: RequestHandler = async (
  req: IGetResearchGroupByIdReq,
  res: Response
) => {
  try {
    const researchGroup = await ResearchGroupService.getResearchGroupById(
      req.params.id
    );

    res.status(200).json({
      data: researchGroup,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[researchGroups.controller][getResearchGroupById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "课题组信息获取失败！",
    });
  }
};

/**
 * Get researchGroup record based on user id provided
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const getResearchGroupByUserId: RequestHandler = async (
  req: IGetResearchGroupByIdReq,
  res: Response
) => {
  try {
    const appliedGroups = await ResearchGroupService.getResearchGroupByOwnerId (
      req.params.id
    );

    const appliedGroupsIds: number[]=[];
    appliedGroups.map((appGroup) => {
      appliedGroupsIds.push(appGroup.id);
    })

    const allGroups = await ResearchGroupService.getResearchGroups();  
    let participatedGroups: any[] = [];
    allGroups.forEach((group) => {
      const members = group.researchGroupMembers?.length > 0
                ? JSON.parse(group.researchGroupMembers as unknown as string)
                : [];
      let isIn = false;
      members.forEach((item: any) => {
        if (req.params.id === (item as any).researchGroupMemberId.toString() && !appliedGroupsIds.includes(group.id)) {
          isIn = true;
        }
      })
      if (isIn) {
        participatedGroups.push(group);
      }
    })

    res.status(200).json({
      data: {
        applied: appliedGroups,
        participated: participatedGroups
      },
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[researchGroups.controller][getResearchGroupByUserId][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "课题组信息列表获取失败！",
    });
  }
};

/**
 * Inserts a new researchGroup record
 *
 * @param req Express Request
 * @param res Express Response
 */
export const addResearchGroup: RequestHandler = async (
  req: IAddResearchGroupReq,
  res: Response
) => {
  try {
    req.body.createdTime = new Date(Date.now());
    req.body.updatedTime = req.body.createdTime;
    req.body.researchGroupCreatedDate = req.body.researchGroupCreatedDate
      ? new Date(req.body.researchGroupCreatedDate).toISOString().slice(0, 10)
      : null;
    const memberList = req.body.researchGroupMembers;
    req.body.researchGroupMembers = req.body.researchGroupMembers?.length > 0? JSON.stringify(req.body.researchGroupMembers) : "";
    const result = await ResearchGroupService.insertResearchGroup(req.body);


    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[researchGroups.controller][addResearchGroup][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    if (error.code === "ER_DUP_ENTRY") {
      res.status(500).json({
        message: "课题组名称重复，请重新输入！",
      });
    } else {
      res.status(500).json({
        message: "课题组保存失败！",
      });
    }
  }
};

/**
 * Updates existing researchGroup record
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const updateResearchGroupById: RequestHandler = async (
  req: IUpdateResearchGroupReq,
  res: Response
) => {
  try {
    req.body.updatedTime = new Date(Date.now());
    req.body.researchGroupCreatedDate = req.body.researchGroupCreatedDate
      ? new Date(req.body.researchGroupCreatedDate).toISOString().slice(0, 10)
      : null;
    
    const memberList = req.body.researchGroupMembers;
    req.body.researchGroupMembers = req.body.researchGroupMembers?.length > 0? JSON.stringify(req.body.researchGroupMembers) : "";
    const result = await ResearchGroupService.updateResearchGroup({
      ...req.body,
      id: req.params.id,
    });

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[researchGroups.controller][updateResearchGroupById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    if (error.code === "ER_DUP_ENTRY") {
      res.status(500).json({
        message: "课题组名称重复，请重新输入！",
      });
    } else {
      res.status(500).json({
        message: "课题组更新失败！",
      });
    }
  }
};

/**
 * deletes a researchGroup
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const deleteResearchGroupById: RequestHandler = async (
  req: IDeleteResearchGroupReq,
  res: Response
) => {
  try {
    const result = await ResearchGroupService.deleteResearchGroup(
      req.params.id
    );

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[researchGroups.controller][deleteResearchGroupById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "课题组删除失败！",
    });
  }
};
